﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WH.Contracts.Select;
using WH.Contracts.Systems.Organizations;
using WH.Model.OrgContext;
using WH.Model.Systems;
using WH.Services.IServices.ISystem;
using Rw.Core.Common;
using Rw.Core.Common.Paging;
using Rw.Core.Document;
using WH.Common.Constant;
using WH.Common.Helper;
using WH.Common.Paging;
using WH.Common.UniOfWork;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WH.WebApi.Controllers.Systems
{
    /// <summary>
    /// 机构信息说明表接口
    /// </summary>
    [Authorize, Route("Organizations"), ApiController]
    public class OrganizationsController : BaseController
    {
        private readonly IRoleService roleService;
        private readonly IMenuService menuService;
        private readonly IRolePermissionService rolePermissionService;
        private readonly IOrganizationService organizationService;
        private readonly IKeyValueService keyValueService;
        private readonly IUnitOfWork unitOfWork;

        private readonly OrganizationContext organizationContext;


        /// <summary>
        /// 机构
        /// </summary>
        public OrganizationsController(
                                            IRoleService roleService,
                                            IMenuService menuService,
                                            IRolePermissionService rolePermissionService,
                                            IOrganizationService organizationService,
                                            IKeyValueService keyValueService,
                                             IUnitOfWork unitOfWork,
                                            OrganizationContext organizationContext
            )
        {
            this.roleService = roleService ?? throw new ArgumentNullException(nameof(roleService));
            this.menuService = menuService ?? throw new ArgumentNullException(nameof(menuService));
            this.rolePermissionService = rolePermissionService ?? throw new ArgumentNullException(nameof(rolePermissionService));
            this.organizationService = organizationService ?? throw new ArgumentNullException(nameof(organizationService));
            this.keyValueService = keyValueService;
            this.unitOfWork = unitOfWork;
            this.organizationContext = organizationContext;
        }


        /// <summary>
        /// 根据机构id获取机构
        /// </summary>
        /// <param name="id">机构Id</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResultResponse<OrganizationOutputDto>> GetOrganizationByIdAsync(string id)
        {
            var organization = await organizationService.FindByIdAsync(id);

            if (organization == null)
            {
                return Error<OrganizationOutputDto>("未查找到该机构，请重新操作");
            }

            var res = new OrganizationOutputDto
            {
                Id = organization.Id,
                ParentId = organization.ParentId,
                Code = organization.Code,
                Name = organization.Name,
                IsEnable = organization.IsEnable,
                Remark = organization.Remark,
                ContactAddress = organization.ContactAddress,
                ImageUrl = organization.ImageUrl,
                ManagerEmail = organization.ManagerEmail,
                ManagerFax = organization.ManagerFax,
                ManagerPhone = organization.ManagerPhone,
                ManagerTel = organization.ManagerTel,
                ManagerWeiXin = organization.ManagerWeiXin,
                ManagerName = organization.ManagerName,
                PostalCode = organization.PostalCode,
                Layer = organization.Layer,
                LayerString = $"{GetLayerString((organization.Layer + 1))}级",
                IsLeaf = organization.IsLeaf,
                TypeCode = organization.TypeCode,
                TypeName = organization.OrgType?.Name,
            };

            return Success(res);
        }

        /// <summary>
        /// 添加机构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task<ResultResponse> PostAsync([FromBody] OrganizationInputDto input)
        {

            var isSuperAdmin = LoginDto.IsAdmin;

            if (string.IsNullOrWhiteSpace(input.ParentId))
            {
                return Error("上级机构id不能为空");
            }

            var isTopOrg = input.ParentId == BusinessFunction.TopParentId;
            if (isTopOrg && !isSuperAdmin)
            {
                return Error("无添加顶级机构权限");
            }

            var exist = await organizationService.ExistsAsync(a => a.Code == input.Code);
            if (exist)
            {
                return Error("请确保机构编号唯一，请重新操作");
            }

            var id = Snowflake.GetNewId();
            var layer = 0;
            var link = $"{id}";
            var isLeaf = true;
            if (!string.IsNullOrWhiteSpace(input.ParentId) && input.ParentId != BusinessFunction.TopParentId)
            {
                var parent = await organizationService.FindByIdAsync(input.ParentId);
                if (parent == null)
                {
                    return Error("上级机构不存在，请重新操作");
                }

                layer = parent.Layer + 1;
                link = $"{parent.Link}|{link}";

                parent.IsLeaf = false;
                await organizationService.UpdateAsync(parent);
            }

            var organization = new OrganizationEntity
            {
                Id = id,
                ParentId = input.ParentId,
                Code = input.Code,
                Name = input.Name,
                IsEnable = input.IsEnable,
                SortCode = input.SortCode,
                Layer = layer,
                Link = link,
                IsLeaf = isLeaf,
                Remark = input.Remark,
                CreatedBy = $"{LoginUserId}|{LoginUserName}",
                CreatedTime = DateTime.Now,
                UpdatedBy = $"{LoginUserId}|{LoginUserName}",
                UpdatedTime = DateTime.Now,

                ContactAddress = input.ContactAddress,
                ImageUrl = input.ImageUrl,
                ManagerEmail = input.ManagerEmail,
                ManagerFax = input.ManagerFax,
                ManagerPhone = input.ManagerPhone,
                ManagerTel = input.ManagerTel,
                ManagerWeiXin = input.ManagerWeiXin,
                ManagerName = input.ManagerName,
                PostalCode = input.PostalCode,
                TypeCode = input.TypeCode,
            };

            try
            {
                await unitOfWork.BeginTranAsync();

                var res = await organizationService.CreateAsync(organization);


                var role = new RoleEntity
                {
                    Id = Snowflake.GetNewId(),
                    Code = BusinessFunction.RoleTypeCode_GLY,
                    Name = "管理员",
                    SortCode = 0,
                    IsEnable = true,
                    TypeCode = BusinessFunction.RoleTypeCode_GLY,
                    OrganizationId = organization.Id,
                };

                var roleResult = await roleService.CreateAsync(role);

                if (roleResult > 0)
                {
                    var menus = await menuService.FindAllAsync();
                    var rolePermissions = new List<RolePermissionEntity>();
                    foreach (var menu in menus)
                    {
                        var rolePermission = new RolePermissionEntity
                        {
                            Id = Snowflake.GetNewId(),
                            RoleType = 1,
                            RoleId = role.Id,
                            ResourceId = menu.Id,
                            OrganizationId = organization.Id,
                            ResourceType = menu.MenuType,
                            IsEnable = true
                        };

                        rolePermissions.Add(rolePermission);
                    }

                    if (rolePermissions.Any())
                    {
                        await rolePermissionService.CreateAsync(rolePermissions);
                    }
                }

                await unitOfWork.CommitTranAsync();

                return res > 0 ? Success() : Error();
            }
            catch (Exception ex)
            {
                await unitOfWork.RollbackTranAsync();

                throw;
            }
        }

        /// <summary>
        /// 下载机构导入模板
        /// </summary>
        /// <returns></returns>
        [HttpGet("download/template")]
        public async Task<ActionResult> DownloadDeviceImportTemplateAsync()
        {
            var result = GetExcelTemplateFile("机构导入标准模板.xls");
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 机构列表导入
        /// </summary>
        /// <returns></returns>
        [HttpPost("import")]
        public async Task<ResultResponse> ImportOrganizationAsync(IFormFile file)
        {
            var result = new ResultResponse();
            try
            {
                var fileName = file.FileName;
                var extension = Path.GetExtension(fileName);
                if (extension == null)
                {
                    return Error("请上传Excel文件");
                }

                var ex = extension.ToLower();
                if (ex is not ".xls" and not ".xlsx")
                {
                    return Error("请上传Excel文件");
                }

                var stream = file.OpenReadStream();
                var dataSet = ExcelHelper.Read(stream, fileName, true);

                var dataTableTag = dataSet.Tables["机构"];
                var tagImports = default(IEnumerable<OrganizationsImport>);
                if (dataTableTag != null)
                {
                    tagImports = TableHelper.ToEntitiesWithPropertyDescription<OrganizationsImport>(dataTableTag);
                }
                else
                {
                    return Error("请导入模板正确的Execl文件");
                }


                if (tagImports is not null && tagImports.Any())
                {
                    var orId = tagImports.Select(s => s.Id).Distinct().ToList();
                    var org = await organizationService.FindAllAsync(g => orId.Contains(g.Id));

                    var organs = await organizationService.FindAllAsync();

                    var addOrg = new List<OrganizationEntity>();
                    foreach (var import in tagImports)
                    {
                        var orgs = new OrganizationEntity
                        {
                            Id = Snowflake.GetNewId(),
                            Code = import.Code ?? string.Empty,
                            Name = import.Name ?? string.Empty,
                            ParentId = organs.FirstOrDefault(x => x.Code == import.ParentCode)?.Id,
                            Remark = import.Remark,
                            IsEnable = import.IsEnable,
                            SortCode = import.SortCode,
                        };

                        addOrg.Add(orgs);
                    }

                    try
                    {
                        if (addOrg.Any())
                        {
                            foreach (var item in addOrg)
                            {
                                var isSuperAdmin = BusinessFunction.SuperAdminId == OrganizationId;
                                var isTopOrg = string.IsNullOrWhiteSpace(item.ParentId);
                                if (isTopOrg && !isSuperAdmin)
                                {
                                    return Error("无添加顶级机构权限");
                                }

                                var exist = await organizationService.ExistsAsync(a => a.Code == item.Code);
                                if (exist)
                                {
                                    return Error("请确保机构编号唯一，请重新操作");
                                }

                                var id = Snowflake.GetNewId();
                                var layer = 0;
                                var link = $"{id}";
                                var isLeaf = true;
                                if (!string.IsNullOrWhiteSpace(item.ParentId))
                                {
                                    var parent = await organizationService.FindByIdAsync(item.ParentId);
                                    if (parent == null)
                                    {
                                        return Error("上级机构不存在，请重新操作");
                                    }

                                    layer = parent.Layer + 1;
                                    link = $"{parent.Link}|{link}";

                                    parent.IsLeaf = false;
                                    await organizationService.UpdateAsync(parent);
                                }

                                var organization = new OrganizationEntity
                                {
                                    Id = id,
                                    ParentId = item.ParentId,
                                    Code = item.Code,
                                    Name = item.Name,
                                    IsEnable = item.IsEnable,
                                    SortCode = item.SortCode,
                                    Layer = layer,
                                    Link = link,
                                    IsLeaf = isLeaf,
                                    Remark = item.Remark,
                                    CreatedBy = $"{LoginUserId}|{LoginUserName}",
                                    CreatedTime = DateTime.Now,
                                    UpdatedBy = $"{LoginUserId}|{LoginUserName}",
                                    UpdatedTime = DateTime.Now,
                                };

                                var res = await organizationService.CreateAsync(organization);


                                var role = new RoleEntity
                                {
                                    Id = Snowflake.GetNewId(),
                                    Code = "GLY",
                                    Name = "管理员",
                                    SortCode = 0,
                                    IsEnable = true,
                                    //Type = RoleTypeEnum.Admin,
                                    OrganizationId = organization.Id,
                                };

                                var roleResult = await roleService.CreateAsync(role);

                                if (roleResult > 0)
                                {
                                    var menuOrgId = isTopOrg ? isSuperAdmin ? BusinessFunction.SuperAdminId : null : item.ParentId;

                                    var menus = await menuService.FindAllAsync(m => menuOrgId == m.OrganizationId);
                                    var rolePermissions = new List<RolePermissionEntity>();
                                    foreach (var menu in menus)
                                    {
                                        var newId = Snowflake.GetNewId();
                                        menus.ToList().FindAll(m => m.ParentId == menu.Id).ForEach(m => m.ParentId = newId);

                                        menu.Id = newId;
                                        menu.OrganizationId = organization.Id;
                                        var rolePermission = new RolePermissionEntity
                                        {
                                            Id = Snowflake.GetNewId(),
                                            RoleType = 1,
                                            RoleId = role.Id,
                                            ResourceId = menu.Id,
                                            OrganizationId = organization.Id,
                                        };

                                        rolePermissions.Add(rolePermission);
                                    }

                                    if (rolePermissions.Any())
                                    {
                                        await menuService.CreateAsync(menus);
                                        await rolePermissionService.CreateAsync(rolePermissions);
                                    }
                                }
                            }

                            await organizationService.CreateAsync(addOrg);
                        }

                        return Success("导入成功");
                    }
                    catch (Exception)
                    {
                        return Error("导入失败");
                    }
                }
                else
                {
                    return Error("请检查Excel文件中‘机构’工作表是否有数据，再重新尝试导入！");
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 编辑机构
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResultResponse> PutAsync(string id, [FromBody] OrganizationInputDto input)
        {
            if (id == input.ParentId)
            {
                return Error("不能将自身作为父级节点，请检查");
            }

            var isSuperAdmin = LoginDto.IsAdmin;
            var isTopOrg = string.IsNullOrWhiteSpace(input.ParentId);
            if (isTopOrg && !isSuperAdmin)
            {
                return Error("无添加顶级机构权限");
            }

            var exist = await organizationService.ExistsAsync(a => a.Id != id && a.Code == input.Code);
            if (exist)
            {
                return Error("请确保机构编号唯一，请重新操作");
            }

            var organization = await organizationService.FindByIdAsync(id);
            if (organization == null)
            {
                return Error("未查找到该机构，请重新操作");
            }

            var layer = 0;
            var link = $"{id}";
            if (!string.IsNullOrWhiteSpace(input.ParentId))
            {
                var parent = await organizationService.FindByIdAsync(input.ParentId);
                if (parent == null && input.ParentId != BusinessFunction.TopParentId)
                {
                    return Error("上级机构不存在，请重新操作");
                }
                if (input.ParentId != BusinessFunction.TopParentId)
                {
                    layer = parent.Layer + 1;
                    link = $"{parent.Link}|{link}";
                }
                if (parent != null)
                {
                    if (parent.Id != organization.ParentId && !string.IsNullOrWhiteSpace(organization.ParentId))
                    {
                        var oldParent = await organizationService.FindByIdAsync(organization.ParentId);
                        if (oldParent != null)
                        {
                            var oldParentHasChildren = await organizationService.ExistsAsync(a => a.ParentId == parent.Id && a.Id != id);
                            oldParent.IsLeaf = !oldParentHasChildren;
                            await organizationService.UpdateAsync(oldParent);
                        }
                    }
                }
                else
                {
                    if (input.ParentId == BusinessFunction.TopParentId && !string.IsNullOrWhiteSpace(organization.ParentId))
                    {
                        var oldParent = await organizationService.FindByIdAsync(organization.ParentId);
                        if (oldParent != null)
                        {
                            var oldParentHasChildren = await organizationService.ExistsAsync(a => a.ParentId == organization.ParentId && a.Id != id);
                            oldParent.IsLeaf = !oldParentHasChildren;
                            await organizationService.UpdateAsync(oldParent);
                        }
                    }
                }

                if (parent != null)
                {
                    parent.IsLeaf = false;
                    await organizationService.UpdateAsync(parent);
                }
            }

            var hasChildren = await organizationService.ExistsAsync(a => a.ParentId == id);
            var isLeaf = !hasChildren;

            organization.ParentId = input.ParentId;
            organization.Code = input.Code;
            organization.Name = input.Name;
            organization.IsEnable = input.IsEnable;
            organization.SortCode = input.SortCode;
            organization.Remark = input.Remark;
            organization.Link = link;
            organization.Layer = layer;
            organization.IsLeaf = isLeaf;
            organization.UpdatedBy = $"{LoginUserId}|{LoginUserName}";
            organization.UpdatedTime = DateTime.Now;

            organization.ManagerEmail = input.ManagerEmail;
            organization.ManagerFax = input.ManagerFax;
            organization.ManagerPhone = input.ManagerPhone;
            organization.ManagerWeiXin = input.ManagerWeiXin;
            organization.ManagerTel = input.ManagerTel;
            organization.ManagerName = input.ManagerName;
            organization.ContactAddress = input.ContactAddress;
            organization.ImageUrl = input.ImageUrl;
            organization.PostalCode = input.PostalCode;
            organization.TypeCode = input.TypeCode;
            //organization.TypeName = await GetTypeName(input.TypeCode);

            var res = await organizationService.UpdateAsync(organization);

            return res > 0 ? Success() : Error();
        }

        /// <summary>
        ///机构删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResultResponse> DeleteAsync(string id)
        {
            var org = await organizationService.FindByIdAsync(id);
            if (org == null)
            {
                return Error("此机构不存在");
            }
            var fid = org.Id;
            var hasChildren = await organizationService.FindAllAsync(a => a.ParentId.Equals(fid));
            if (hasChildren.Any())
            {
                return Error("请先删除此机构下的子机构，再删除此机构");
            }

            if (!string.IsNullOrWhiteSpace(org.ParentId))
            {
                var parent = await organizationService.FindByIdAsync(org.ParentId);
                if (parent != null)
                {
                    var pid = parent.Id;
                    var parentHasChildren = await organizationService.AnyAsync(o => o.ParentId == pid && o.Id != fid);
                    parent.IsLeaf = !parentHasChildren;
                    await organizationService.UpdateAsync(parent);
                }
            }

            var res = await organizationService.SoftRemoveAsync(org);

            //await roleService.RemoveAsync(o => o.OrganizationId == id);
            //await menuService.RemoveAsync(o => o.OrganizationId == id);
            //await rolePermissionService.RemoveAsync(o => o.OrganizationId == id);

            return res ? Success() : Error();
        }

        /// <summary>
        /// 基础机构列表数据
        /// </summary>
        /// <param name="pager">分页</param>
        /// <param name="filter">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<ResultResponse<IPagedList<OrganizationOutputByPageDto>>> GetOrganizationsByPageAsync([FromQuery] PageParam pager, [FromQuery] OrganizationFilterDto filter)
        {
            var filterData = new OrganizationFilter();
            if (filter != null)
            {
                filterData.Keyword = filter.Keyword;
                filterData.Code = filter.Code;
                filterData.Name = filter.Name;
                filterData.IsEnable = filter.IsEnable;
            }

            if (LoginDto.IsAdmin == true)
            {
                //filterData.ParentId = LoginDto.OrganizationId;
            }
            else
            {
                filterData.Id = LoginDto.OrganizationId;
            }

            var pagedList = await organizationService.GetOrganizationsByPageAsync(pager, filterData);

            var pages = pagedList.Entities;

            var reslist = new List<OrganizationOutputByPageDto>();
            foreach (var item in pages)
            {
                var dto = new OrganizationOutputByPageDto()
                {
                    Id = item.Id,
                    ParentId = item.ParentId,
                    HasChildren = !item.IsLeaf,
                    Code = item.Code,
                    Name = item.Name,
                    IsEnable = item.IsEnable,
                    CreatedTime = item.CreatedTime,
                    IsLeaf = item.IsLeaf,
                    Layer = item.Layer,
                    LayerString = $"{GetLayerString((item.Layer + 1))}级",
                    Children = await GetChildOrganizations(item.Id, filterData.IsEnable),
                    TypeName = item.OrgType?.Name,
                    TypeCode = item.TypeCode,
                };

                reslist.Add(dto);
            }

            var data = new PagedList<OrganizationOutputByPageDto>()
            {
                PageIndex = pagedList.PageIndex,
                PageSize = pagedList.PageSize,
                TotalCount = pagedList.TotalCount,
                Entities = reslist
            };

            return Success<IPagedList<OrganizationOutputByPageDto>>(data);
        }

        /// <summary>
        /// 机构列表数据（只获取一级）
        /// </summary>
        /// <param name="parentId">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("Tree/{parentId}")]
        public async Task<ResultResponse<IList<OrganizationOutputByPageDto>>> GetOrganizationsByTreeWithParentIdAsync(string parentId)
        {
            var list = await organizationService.FindAllAsync(o => o.ParentId == parentId && o.IsEnable);
            var clist = await organizationService.FindAllAsync(o => o.IsEnable);
            //var depts = await departmentRepository.FindAllAsync();
            var data = list.Select(item => new OrganizationOutputByPageDto
            {
                Id = item.Id,
                ParentId = item.ParentId,
                HasChildren = clist.Any(c => c.ParentId == item.Id),
                Code = item.Code,
                Name = item.Name,
                IsEnable = item.IsEnable,
                CreatedTime = item.CreatedTime,
                IsLeaf = item.IsLeaf,
                Layer = item.Layer,
                LayerString = $"{GetLayerString((item.Layer + 1))}级",
                TypeCode = item.TypeCode,
                TypeName = item.OrgType?.Name,
            }).ToList();

            return Success<IList<OrganizationOutputByPageDto>>(data);
        }

        /// <summary>
        /// 机构列表数据（获取所有子级）
        /// </summary>
        /// <param name="parentId">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("TreeAll/{parentId}")]
        public async Task<ResultResponse<IList<OrganizationOutputByPageDto>>> GetOrganizationsByTreeAllWithParentIdAsync(string parentId)
        {
            var clist = await organizationService.FindAllAsync(o => o.IsEnable);

            var list = clist.Where(o => o.ParentId == parentId && o.IsEnable);
            //var depts = await departmentRepository.FindAllAsync();
            var data = list.Select(item => new OrganizationOutputByPageDto
            {
                Id = item.Id,
                ParentId = item.ParentId,
                HasChildren = clist.Any(c => c.ParentId == item.Id),
                Code = item.Code,
                Name = item.Name,
                IsEnable = item.IsEnable,
                CreatedTime = item.CreatedTime,
                IsLeaf = item.IsLeaf,
                Layer = item.Layer,
                LayerString = $"{GetLayerString((item.Layer + 1))}级",
                TypeCode = item.TypeCode,
                TypeName = item.OrgType?.Name,
            }).ToList();

            foreach (var item in data)
            {
                if (item.HasChildren)
                {
                    item.Children = await GetChildOrganizations(item.Id, true);
                }
            }

            return Success<IList<OrganizationOutputByPageDto>>(data);
        }

        /// <summary>
        /// 当前登录用户机构列表数据（获取所有子级）
        /// </summary>
        /// <param name="parentId">查询实体参数请求</param>
        /// <returns></returns>
        [HttpGet("TreeAllByLogin")]
        public async Task<ResultResponse<IList<OrganizationOutputByPageDto>>> GetOrganizationsByTreeAllWithLoginAsync()
        {
            var clist = await organizationService.FindAllAsync(o => o.IsEnable);

            var list = new List<OrganizationEntity>();

            if (LoginDto.IsAdmin)
            {
                list = clist.Where(o => o.ParentId == OrganizationId && o.IsEnable).ToList();
            }
            else
            {
                list = clist.Where(o => o.Id == OrganizationId && o.IsEnable).ToList();
            }

            //var depts = await departmentRepository.FindAllAsync();
            var data = list.Select(item => new OrganizationOutputByPageDto
            {
                Id = item.Id,
                ParentId = item.ParentId,
                HasChildren = clist.Any(c => c.ParentId == item.Id),
                Code = item.Code,
                Name = item.Name,
                IsEnable = item.IsEnable,
                CreatedTime = item.CreatedTime,
                IsLeaf = item.IsLeaf,
                Layer = item.Layer,
                LayerString = $"{GetLayerString((item.Layer + 1))}级",
                TypeCode = item.TypeCode,
                TypeName = item.OrgType?.Name,
            }).ToList();

            foreach (var item in data)
            {
                if (item.HasChildren)
                {
                    item.Children = await GetChildOrganizations(item.Id, true);
                }
            }

            return Success<IList<OrganizationOutputByPageDto>>(data);
        }




        /// <summary>
        /// 机构下拉列表数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("Select")]
        public async Task<ResultResponse<IList<OutputBySelectDto>>> GetOrganizationsBySelectAsync()
        {
            IEnumerable<OrganizationEntity> list = new List<OrganizationEntity>();
            list = await organizationService.GetOrganizeSelfAndSubsAsync(OrganizationId);

            var res = list.Select(o => new OutputBySelectDto
            {
                Id = o.Id,
                Name = o.Name,
                ParentId = o.ParentId,
            }).ToList();

            return Success<IList<OutputBySelectDto>>(res);
        }

        private async Task<IList<OrganizationOutputByPageDto>> GetChildOrganizations(string parentId, bool? status)
        {
            var all = await organizationService.FindAllAsync(null, true);

            var data = all.Where(o => o.ParentId == parentId);

            if (status.HasValue)
            {
                data = data.Where(x => x.IsEnable == status.Value);
            }

            var list = data.Select(x => new OrganizationOutputByPageDto
            {
                Id = x.Id,
                ParentId = x.ParentId,
                HasChildren = !x.IsLeaf,
                Code = x.Code,
                Name = x.Name,
                IsEnable = x.IsEnable,
                CreatedTime = x.CreatedTime,
                Layer = x.Layer,
                LayerString = $"{GetLayerString((x.Layer + 1))}级",
                IsLeaf = x.IsLeaf,
                TypeCode = x.TypeCode,
                TypeName = x.OrgType?.Name,
            }).ToList();

            foreach (var item in list)
            {
                item.Children = await GetChildOrganizations(item.Id, status);

                item.HasChildren = item.Children.Any();
            }
            return list;
        }

        private IList<string> GetOrganizationIds(IList<OrganizationOutputByPageDto> dtos)
        {
            var list = new List<string>();

            list.AddRange(dtos.Select(x => x.Id));

            foreach (var d in dtos)
            {
                list.AddRange(GetOrganizationIds(d.Children));
            }
            return list;
        }

        //private async Task<string> GetTypeName(string typeCode)
        //{
        //    var keyValue = await keyValueService.GetKeyValueByCodeAsync(typeCode);

        //    return keyValue?.Name ?? "";
        //}


        private string GetLayerString(int level)
        {
            return level.ConvertToChinese();
        }
    }
}